package electricity.WebSocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import electricity.dto.DeviceQueryDTO;
import electricity.service.DeviceService;
import electricity.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

@Component
@Slf4j
public class DeviceWebSocketHandler extends TextWebSocketHandler {

    private final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    // 存储每个客户端的分页状态（sessionId -> 分页信息）
    private final Map<String, PageInfo> sessionPageInfo = new HashMap<>();

    @Autowired
    private DeviceService deviceService;

    // 分页信息类
    private static class PageInfo {
        private int page;
        private int pageSize;
        private String deviceId;

        public PageInfo(int page, int pageSize, String deviceId) {
            this.page = page;
            this.pageSize = pageSize;
            this.deviceId = deviceId;
        }

        // getters and setters
        public int getPage() { return page; }
        public int getPageSize() { return pageSize; }
        public String getDeviceId() { return deviceId; }
        public void setPage(int page) { this.page = page; }
        public void setPageSize(int pageSize) { this.pageSize = pageSize; }
        public void setDeviceId(String deviceId) { this.deviceId = deviceId; }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        // 初始化分页信息为第一页
        sessionPageInfo.put(session.getId(), new PageInfo(1, 10, null));
        // 连接建立时发送第一页数据
        sendDeviceData(session, 1, 10, null);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
        sessionPageInfo.remove(session.getId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        log.info("收到客户端消息: {}", payload);

        try {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> request = mapper.readValue(payload, Map.class);

            // 解析分页参数
            int page = (int) request.getOrDefault("page", 1);
            int pageSize = (int) request.getOrDefault("pageSize", 10);

            // 解析设备ID参数（可能为null）
            String deviceId = (String) request.get("deviceId");

            // 更新该客户端的分页状态
            PageInfo pageInfo = sessionPageInfo.get(session.getId());
            if (pageInfo != null) {
                pageInfo.setPage(page);
                pageInfo.setPageSize(pageSize);
                pageInfo.setDeviceId(deviceId);
            }

            // 使用分页和设备ID参数查询数据
            sendDeviceData(session, page, pageSize, deviceId);
        } catch (Exception e) {
            log.error("解析消息失败", e);
            // 发送错误响应给客户端
            session.sendMessage(new TextMessage("{\"error\": \"解析消息失败\"}"));
        }
    }

    private void sendDeviceData(WebSocketSession session, int page, int pageSize, String deviceId) throws IOException {
        log.info("开始发送分页数据给客户端: page={}, pageSize={}, deviceId={}", page, pageSize, deviceId);

        DeviceQueryDTO deviceQueryDTO = new DeviceQueryDTO();
        deviceQueryDTO.setPage(page);
        deviceQueryDTO.setPageSize(pageSize);

        // 设置设备ID（如果不为null）
        if (deviceId != null && !deviceId.isEmpty()) {
            try {
                deviceQueryDTO.setDeviceId(Integer.valueOf(deviceId));
            } catch (NumberFormatException e) {
                log.error("无效的设备ID格式: {}", deviceId);
                session.sendMessage(new TextMessage("{\"error\": \"无效的设备ID格式\"}"));
                return;
            }
        }

        PageResult pageResult = deviceService.paramspageQuery(deviceQueryDTO);
        String jsonResponse = new ObjectMapper().writeValueAsString(pageResult);
        session.sendMessage(new TextMessage(jsonResponse));
        log.info("已发送数据: {}", jsonResponse);
    }

    public void sendUpdatesToAll() {
        sessions.forEach(session -> {
            try {
                // 获取该客户端的当前分页状态
                PageInfo pageInfo = sessionPageInfo.get(session.getId());
                if (pageInfo != null) {
                    // 使用客户端当前的分页状态推送数据
                    sendDeviceData(session, pageInfo.getPage(), pageInfo.getPageSize(), pageInfo.getDeviceId());
                } else {
                    // 如果没有记录分页信息，默认使用第一页
                    sendDeviceData(session, 1, 10, null);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
